import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  message,
  Card,
  Row,
  Col,
  DatePicker,
  Descriptions,
  Timeline,
  InputNumber,
  Image,
  Badge,
  Tabs,
  Statistic,
  Alert
} from 'antd';
import {
  SearchOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  MessageOutlined,
  DollarOutlined,
  ShoppingOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined,
  ExportOutlined
} from '@ant-design/icons';
import { refundAPI } from '../../services/api';
import { useAdminAuth } from '../../hooks/useAuth';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { TabPane } = Tabs;

const AdminRefunds = () => {
  const [loading, setLoading] = useState(false);
  const [refunds, setRefunds] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [searchForm] = Form.useForm();
  const [reviewForm] = Form.useForm();
  const [detailVisible, setDetailVisible] = useState(false);
  const [reviewVisible, setReviewVisible] = useState(false);
  const [selectedRefund, setSelectedRefund] = useState(null);
  const [activeTab, setActiveTab] = useState('all');
  const [statistics, setStatistics] = useState({
    pending: 0,
    processing: 0,
    approved: 0,
    rejected: 0,
    totalAmount: 0
  });
  const { hasAdminPermission } = useAdminAuth();

  // 统一的按钮样式
  const buttonStyle = {
    height: '32px',
    fontSize: '14px',
    fontWeight: '400',
    borderRadius: '6px'
  };

  const primaryButtonStyle = {
    height: '32px',
    fontSize: '14px',
    fontWeight: '500',
    borderRadius: '6px'
  };

  useEffect(() => {
    loadRefunds();
    loadStatistics();
  }, [activeTab]);

  const loadRefunds = async (params = {}) => {
    setLoading(true);
    try {
      const statusFilter = activeTab === 'all' ? {} : { status: activeTab };
      const response = await refundAPI.getRefunds({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...statusFilter,
        ...params
      });
      
      if (response.success) {
        setRefunds(response.data.list);
        setPagination(prev => ({
          ...prev,
          total: response.data.total
        }));
      }
    } catch (error) {
      message.error('加载售后列表失败');
    } finally {
      setLoading(false);
    }
  };

  const loadStatistics = async () => {
    try {
      const response = await refundAPI.getRefundStatistics();
      if (response.success) {
        setStatistics(response.data);
      }
    } catch (error) {
      console.error('加载统计数据失败:', error);
    }
  };

  const handleSearch = () => {
    const values = searchForm.getFieldsValue();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadRefunds(values);
  };

  const handleReset = () => {
    searchForm.resetFields();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadRefunds();
  };

  const handleRefresh = () => {
    loadRefunds();
    loadStatistics();
  };

  const handleViewDetail = (refund) => {
    setSelectedRefund(refund);
    setDetailVisible(true);
  };

  const handleReview = (refund) => {
    setSelectedRefund(refund);
    reviewForm.resetFields();
    setReviewVisible(true);
  };

  const handleReviewSubmit = async () => {
    try {
      const values = await reviewForm.validateFields();
      const response = await refundAPI.reviewRefund(selectedRefund.id, values);
      
      if (response.success) {
        message.success('审核完成');
        setReviewVisible(false);
        loadRefunds();
        loadStatistics();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('审核失败');
    }
  };

  const getRefundTypeText = (type) => {
    const typeMap = {
      'refund_only': '仅退款',
      'refund_return': '退货退款',
      'exchange': '换货'
    };
    return typeMap[type] || type;
  };

  const getStatusConfig = (status) => {
    const statusMap = {
      pending: { color: 'orange', text: '待审核', icon: <ClockCircleOutlined /> },
      processing: { color: 'blue', text: '处理中', icon: <ExclamationCircleOutlined /> },
      approved: { color: 'green', text: '已同意', icon: <CheckCircleOutlined /> },
      rejected: { color: 'red', text: '已拒绝', icon: <CloseCircleOutlined /> },
      completed: { color: 'cyan', text: '已完成', icon: <CheckCircleOutlined /> }
    };
    return statusMap[status] || { color: 'default', text: status };
  };

  const columns = [
    {
      title: '售后单号',
      dataIndex: 'refundNo',
      key: 'refundNo',
      fixed: 'left',
      width: 150,
    },
    {
      title: '关联订单',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 150,
      render: (orderNo) => (
        <a onClick={(e) => e.preventDefault()}>{orderNo}</a>
      ),
    },
    {
      title: '用户',
      dataIndex: 'userName',
      key: 'userName',
      width: 120,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type) => (
        <Tag color="blue">{getRefundTypeText(type)}</Tag>
      ),
    },
    {
      title: '商品信息',
      key: 'productInfo',
      width: 200,
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Image
            width={40}
            height={40}
            src={record.productImage}
            style={{ marginRight: 8 }}
          />
          <div>
            <div style={{ fontSize: '12px' }}>{record.productName}</div>
            <div style={{ fontSize: '12px', color: '#999' }}>
              数量: {record.quantity}
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '退款金额',
      dataIndex: 'refundAmount',
      key: 'refundAmount',
      width: 120,
      render: (amount) => (
        <span style={{ color: '#f5222d', fontWeight: 'bold' }}>
          ¥{amount?.toFixed(2) || '0.00'}
        </span>
      ),
    },
    {
      title: '申请原因',
      dataIndex: 'reason',
      key: 'reason',
      width: 200,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const config = getStatusConfig(status);
        return (
          <Badge
            status={status === 'processing' ? 'processing' : 'default'}
            text={
              <Space>
                {config.icon}
                <span>{config.text}</span>
              </Space>
            }
          />
        );
      },
    },
    {
      title: '申请时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
      render: (time) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EyeOutlined />}
            size="small"
            onClick={() => handleViewDetail(record)}
            style={buttonStyle}
          >
            查看
          </Button>
          
          {hasAdminPermission('refund:review') && ['pending', 'processing'].includes(record.status) && (
            <Button
              type="link"
              icon={<CheckCircleOutlined />}
              size="small"
              onClick={() => handleReview(record)}
              style={buttonStyle}
            >
              审核
            </Button>
          )}
          
          <Button
            type="link"
            icon={<MessageOutlined />}
            size="small"
            style={buttonStyle}
          >
            沟通
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="待审核"
              value={statistics.pending}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#faad14' }}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="处理中"
              value={statistics.processing}
              prefix={<ExclamationCircleOutlined />}
              valueStyle={{ color: '#1890ff' }}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="已完成"
              value={statistics.approved}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="退款总额"
              value={statistics.totalAmount}
              prefix={<DollarOutlined />}
              precision={2}
              valueStyle={{ color: '#f5222d' }}
              loading={loading}
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索表单 */}
      <Card style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="horizontal"
          onFinish={handleSearch}
        >
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="refundNo" label="售后单号">
                <Input placeholder="请输入售后单号" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="orderNo" label="订单号">
                <Input placeholder="请输入订单号" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="type" label="类型">
                <Select placeholder="选择售后类型" allowClear>
                  <Option value="refund_only">仅退款</Option>
                  <Option value="refund_return">退货退款</Option>
                  <Option value="exchange">换货</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Space>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  icon={<SearchOutlined />}
                  style={primaryButtonStyle}
                >
                  搜索
                </Button>
                <Button onClick={handleReset} style={buttonStyle}>重置</Button>
                <Button 
                  icon={<ReloadOutlined />} 
                  onClick={handleRefresh}
                  style={buttonStyle}
                >
                  刷新
                </Button>
              </Space>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="dateRange" label="申请时间">
                <RangePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label=" " colon={false}>
                <Button 
                  icon={<ExportOutlined />}
                  style={buttonStyle}
                >
                  导出数据
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      {/* 售后列表 */}
      <Card title="售后管理">
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="全部" key="all" />
          <TabPane tab={<Badge count={statistics.pending} offset={[10, 0]}>待审核</Badge>} key="pending" />
          <TabPane tab="处理中" key="processing" />
          <TabPane tab="已同意" key="approved" />
          <TabPane tab="已拒绝" key="rejected" />
          <TabPane tab="已完成" key="completed" />
        </Tabs>

        <Alert
          message="温馨提示"
          description="请及时处理待审核的售后申请，避免影响用户体验。退货退款类申请需要用户寄回商品后再进行退款操作。"
          type="info"
          showIcon
          closable
          style={{ marginBottom: 16 }}
        />

        <Table
          columns={columns}
          dataSource={refunds}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
              loadRefunds({ page, pageSize });
            },
          }}
          scroll={{ x: 1500 }}
        />
      </Card>

      {/* 售后详情模态框 */}
      <Modal
        title="售后详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)} style={buttonStyle}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedRefund && (
          <div>
            <Descriptions bordered column={2} style={{ marginBottom: 24 }}>
              <Descriptions.Item label="售后单号">
                {selectedRefund.refundNo}
              </Descriptions.Item>
              <Descriptions.Item label="售后状态">
                <Tag color={getStatusConfig(selectedRefund.status).color}>
                  {getStatusConfig(selectedRefund.status).text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="售后类型">
                <Tag color="blue">{getRefundTypeText(selectedRefund.type)}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="退款金额">
                <span style={{ color: '#f5222d', fontWeight: 'bold' }}>
                  ¥{selectedRefund.refundAmount?.toFixed(2) || '0.00'}
                </span>
              </Descriptions.Item>
              <Descriptions.Item label="关联订单">
                {selectedRefund.orderNo}
              </Descriptions.Item>
              <Descriptions.Item label="申请用户">
                {selectedRefund.userName}
              </Descriptions.Item>
              <Descriptions.Item label="联系电话">
                {selectedRefund.userPhone || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="申请时间">
                {new Date(selectedRefund.createTime).toLocaleString()}
              </Descriptions.Item>
              <Descriptions.Item label="申请原因" span={2}>
                {selectedRefund.reason}
              </Descriptions.Item>
              <Descriptions.Item label="详细说明" span={2}>
                {selectedRefund.description || '-'}
              </Descriptions.Item>
            </Descriptions>

            <h4>商品信息</h4>
            <Table
              columns={[
                {
                  title: '商品',
                  key: 'product',
                  render: () => (
                    <Space>
                      <Image
                        width={60}
                        height={60}
                        src={selectedRefund.productImage}
                      />
                      <div>
                        <div>{selectedRefund.productName}</div>
                        <div style={{ fontSize: '12px', color: '#999' }}>
                          规格: {selectedRefund.productSpec || '默认'}
                        </div>
                      </div>
                    </Space>
                  ),
                },
                { title: '单价', dataIndex: 'price', key: 'price', render: () => `¥${selectedRefund.productPrice}` },
                { title: '数量', dataIndex: 'quantity', key: 'quantity', render: () => selectedRefund.quantity },
                { 
                  title: '小计', 
                  key: 'subtotal',
                  render: () => `¥${(selectedRefund.productPrice * selectedRefund.quantity).toFixed(2)}`
                }
              ]}
              dataSource={[selectedRefund]}
              pagination={false}
              size="small"
              style={{ marginBottom: 24 }}
            />

            <h4>处理记录</h4>
            <Timeline>
              <Timeline.Item color="green">
                {new Date(selectedRefund.createTime).toLocaleString()} - 用户提交售后申请
              </Timeline.Item>
              {selectedRefund.reviewTime && (
                <Timeline.Item color="blue">
                  {new Date(selectedRefund.reviewTime).toLocaleString()} - 
                  管理员审核: {selectedRefund.reviewResult}
                </Timeline.Item>
              )}
              {selectedRefund.completeTime && (
                <Timeline.Item>
                  {new Date(selectedRefund.completeTime).toLocaleString()} - 售后完成
                </Timeline.Item>
              )}
            </Timeline>

            {selectedRefund.images && selectedRefund.images.length > 0 && (
              <>
                <h4>用户上传的图片</h4>
                <Space>
                  {selectedRefund.images.map((img, index) => (
                    <Image
                      key={index}
                      width={100}
                      height={100}
                      src={img}
                    />
                  ))}
                </Space>
              </>
            )}
          </div>
        )}
      </Modal>

      {/* 审核模态框 */}
      <Modal
        title="售后审核"
        open={reviewVisible}
        onOk={handleReviewSubmit}
        onCancel={() => setReviewVisible(false)}
        width={600}
        destroyOnClose
        okButtonProps={{ style: primaryButtonStyle }}
        cancelButtonProps={{ style: buttonStyle }}
      >
        <Form
          form={reviewForm}
          layout="vertical"
        >
          <Alert
            message="审核提示"
            description={`用户申请${selectedRefund ? getRefundTypeText(selectedRefund.type) : ''}，退款金额：¥${selectedRefund?.refundAmount?.toFixed(2) || '0.00'}`}
            type="warning"
            showIcon
            style={{ marginBottom: 16 }}
          />

          <Form.Item
            name="reviewResult"
            label="审核结果"
            rules={[{ required: true, message: '请选择审核结果' }]}
          >
            <Select placeholder="请选择审核结果">
              <Option value="approved">同意</Option>
              <Option value="rejected">拒绝</Option>
            </Select>
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => 
              prevValues.reviewResult !== currentValues.reviewResult
            }
          >
            {({ getFieldValue }) =>
              getFieldValue('reviewResult') === 'approved' && 
              selectedRefund?.type === 'refund_return' ? (
                <Form.Item
                  name="returnAddress"
                  label="退货地址"
                  rules={[{ required: true, message: '请输入退货地址' }]}
                >
                  <TextArea
                    rows={3}
                    placeholder="请输入退货地址，包括收件人、电话、详细地址"
                  />
                </Form.Item>
              ) : null
            }
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => 
              prevValues.reviewResult !== currentValues.reviewResult
            }
          >
            {({ getFieldValue }) =>
              getFieldValue('reviewResult') === 'approved' ? (
                <Form.Item
                  name="refundAmount"
                  label="实际退款金额"
                  rules={[{ required: true, message: '请输入退款金额' }]}
                  initialValue={selectedRefund?.refundAmount}
                >
                  <InputNumber
                    min={0}
                    max={selectedRefund?.refundAmount}
                    precision={2}
                    style={{ width: '100%' }}
                    prefix="¥"
                  />
                </Form.Item>
              ) : null
            }
          </Form.Item>

          <Form.Item
            name="reviewRemark"
            label="审核备注"
            rules={[
              ({ getFieldValue }) => ({
                required: getFieldValue('reviewResult') === 'rejected',
                message: '拒绝时必须填写原因',
              }),
            ]}
          >
            <TextArea
              rows={4}
              placeholder={
                reviewForm.getFieldValue('reviewResult') === 'rejected' ?
                '请输入拒绝原因，将通知用户' :
                '请输入审核备注（可选）'
              }
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AdminRefunds;